require 'rake'
require 'rake/testtask'
require 'rake/rdoctask'
require 'builder/xmlbase'
require 'active_record/fixtures'
#require 'action_controller/base'

namespace :sitemap do
  puts "Started at #{Time.now}"
  LOCATION_OF_ADS_XML = RAILS_ROOT+'/public/sitemap.xml'
  DOMAIN = "kandp.com.ua"
  
  desc "Create sitemap.xml into cache." 
  task :create => :environment do

    yaml_obj = 'db/fixtures/sitemap.yml'
    @static_links = YAML::load(File.open(yaml_obj))
    @services = Service.all
    @articles = Article.all

    File.open(LOCATION_OF_ADS_XML, 'w') do |file|
      file.write generate_xml @static_links, @services, @articles
    end

  puts "Finished at #{Time.now}"
  end

  def generate_xml static_links, services, articles
    include ActionView::Helpers::UrlHelper
    include ActionController::UrlWriter
    default_url_options[:host] = DOMAIN
    default_url_options[:format] = 'html'

    xml = Builder::XmlMarkup.new
    xml.instruct!
    
    xml.urlset :xmlns => "http://www.google.com/schemas/sitemap/0.84" do
      xml.url do
        xml.loc         root_url
        xml.lastmod     Time.now.utc.strftime("%Y-%m-%d")
        xml.changefreq  "always"
        xml.priority    0.9
      end

      static_links.each do |static_link|
        xml.url do
          xml.loc         eval("#{static_link[1]['url']}")
          xml.lastmod     Time.now.utc.strftime("%Y-%m-%d")
          xml.changefreq  "never"
          xml.priority    static_link[1]['priority']
        end
      end

      services.each do |service|
        xml.url do
          xml.loc         formatted_service_url(service.id)
          xml.lastmod     service.updated_at.strftime("%Y-%m-%d")
          xml.changefreq  "monthly"
          xml.priority    0.5
        end
      end
      
      articles.each do |article|
        xml.url do
          xml.loc         formatted_article_url(article.id)
          xml.lastmod     article.updated_at.strftime("%Y-%m-%d")
          xml.changefreq  "monthly"
          xml.priority    0.5
        end
      end

    end

  end
  
end
